package com.example.kuaizu.exception;

import kuaizu.common.exception.MassageException;
import com.example.kuaizu.utils.AjaxResponse;
import kuaizu.common.constp.KuaiZuConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;


@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    //@ExceptionHandler(Exception.class)//表示出现这个异常时执行这个方法
    //public AjaxResponse handleException(Exception e) {
    //    e.printStackTrace();//异常输出控制台;
    //    //判断是否有错误信息有的话返回错误信息没有返回操作失败
    //    return AjaxResponse.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
    //}

    @ExceptionHandler(MassageException.class)
    public AjaxResponse getMassageException(MassageException e) {
        log.error("错误码：{}, 错误信息：{}", e.getCode(), e.getMessage());
        //e.printStackTrace();
        return AjaxResponse.error(e.getMessage());
    }
//sql异常捕获
    @ExceptionHandler(SQLException.class)
    public AjaxResponse getMyBatisSystemException(SQLException e) {
        log.error("错误码：{}, 错误信息：{}", 500, e.getMessage());
        //控制台打印异常
        e.printStackTrace();
        return AjaxResponse.error(500,"操作失败,检查数据是否合法,或者联系管理员修改查看服务器权限");
    }
    //数据格式错误
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public AjaxResponse getHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("错误码：{}, 错误信息：{}", 500, e.getMessage());
        e.printStackTrace();
        return AjaxResponse.error(KuaiZuConst.ERROR,e.getMessage(),"数据格式错误,服务器无法解析,检查json格式是正确");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResponse paramException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .reduce((s1, s2) -> s1 + "; " + s2)
                .orElse(e.getMessage());
        return AjaxResponse.error(KuaiZuConst.ERROR, errorMessage, null);

    }
}